package com.ibeetl.cms.web;

import com.ibeetl.cms.util.RedisLock;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * redis分布式锁测试
 */
@Controller
public class RedisLockController {

    // 超时时间
    private static final long EXTIME = 1 * 1000;

    // 初始1000张票
    private Long num = 1000L;

    // 接收到请求数
    private int i = 0;

    // 失败次数
    private int j = 0;

    @Autowired
    RedisLock redisLock;

    /**
     * 买票
     */
    @RequestMapping("/test/buyTicket")
    @ResponseBody
    public void buyTicket() throws Exception {
        i = i+1; // 记录请求次数
        // 模拟商品id
        String shopId = "ryjhy";
        String time = String.valueOf(System.currentTimeMillis() + EXTIME);
        boolean lock = redisLock.lock(shopId, String.valueOf(time));
        // 如果加锁失败，则变量被占用， 抛异常等待下次请求
        if(!lock){
            // 加锁失败
            j++;
            throw new Exception();
        }
        // =====================
        // 业务代码 ...
        long num1 = getNum();
        Thread.sleep(100);
        num1--;
        setNum(num1);
        // =====================
        redisLock.unlock(shopId,String.valueOf(time));
    }

    @RequestMapping("/test/num")
    @ResponseBody
    public String num(){

        return "剩余：" + getNum() + " ,请求次数： " + i + " ,失败次数： " + j;
    }

    public Long getNum() {
        return num;
    }

    public void setNum(Long num) {
        this.num = num;
    }
}
